<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * 密友
 */
class CloseFriend extends Model
{
    protected $table = 'user_close_friend';
    protected $fillable = ['user_id', 'frd_user_id', 'flag', 'close_value', 'consume_coin', 'consume_ts'];

    /**
     * 添加密友关系
     */
    static function addRecord($userId = 0, $frdUserId = 0)
    {
        $item = self::check($userId, $frdUserId);
        if ($item && $item->flag == 1) return $item;
        return self::updateOrCreate([
            'user_id' => $userId,
            'frd_user_id' => $frdUserId,
        ], [
            'user_id' => $userId,
            'frd_user_id' => $frdUserId,
            'flag' => 1
        ]);
    }

    /**
     * 增加亲密度
     */
    static function addClose($userId = 0, $frdUserId = 0, $closeValue = 0.0, $coin = 0.0)
    {
        $item = self::addRecord($userId, $frdUserId);
        if (!$item) return false;
        // $ret1 = self::where('id', $item->id)->limit(1)->increment('close_value', $closeValue);
        // $ret2 = self::where('id', $item->id)->limit(1)->increment('consume_coin', $coin);
        self::where('id', $item->id)->limit(1)->update([
            'close_value' => $item->close_value + $closeValue,
            'consume_coin' => $item->consume_coin + $coin,
            'consume_ts' => time()
        ]);
        return;
    }

    /**
     * 查询密友关系
     */
    static function check($userId = 0, $frdUserId = 0)
    {
        $where = [
            'user_id' => $userId,
            'frd_user_id' => $frdUserId,
        ];
        $orWhere = [
            'user_id' => $frdUserId,
            'frd_user_id' => $userId,
        ];
        return Db::table('user_close_friend')->where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->first();
    }

    /**
     * 获取密友列表
     */
    static function getFrdList($userId = 0)
    {
        $where = ['user_id' => $userId, 'flag' => 1];
        $orWhere = ['frd_user_id' => $userId, 'flag' => 1];
        $items = Db::table('user_close_friend')->where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->select(['user_id', 'frd_user_id', 'close_value'])->orderBy('close_value', 'desc')->get()->toArray();
        $frdIds = [];
        foreach ($items as $item) {
            if ($item->close_value < 0.1) continue;
            $frdIds[] = $userId == $item->user_id ? $item->frd_user_id : $item->user_id;
        }
        return $frdIds;
    }

    /**
     * 查询两人的亲密度
     */
    static function getCloseValue($userId = 0, $frdUserId = 0)
    {
        $item = self::check($userId, $frdUserId);
        if ($item && $item->flag == 1) {
            $value = round(floor($item->close_value * 100) / 100, 2);
            return $value < 0.1 ? 0.0 : $value;
        }
        return 0.0;
    }

    /**
     * 两人亲密度清零
     */
    static function clearClose($userId = 0, $frdUserId = 0)
    {
        $item = self::check($userId, $frdUserId);
        if (!$item) return true;
        log_user_result($userId, "{$frdUserId}==CloseValue:{$item->close_value}");
        return self::where('id', $item->id)->limit(1)->update([
            'close_value' => 0,
        ]);
    }

    /**
     * 获取配置列表
     */
    static function getSetting()
    {
        return [
            ['level' => '初级', 'level_num' => 0, 'close_value' => 0, 'unlock_content' => '文字聊天，发送语音', 'unlock' => ['voice', 'text']],
            ['level' => '相互吸引', 'level_num' => 1, 'close_value' => 0, 'unlock_content' => '女生拨打语音，视频', 'unlock' => ['voice_call', 'video_call']],
            ['level' => '两情相悦', 'level_num' => 2, 'close_value' => 1, 'unlock_content' => '发送图片，视频', 'unlock' => ['video', 'image']],
            // ['level' => '如胶似漆', 'level_num' => 3, 'close_value' => 666, 'unlock_content' => '查看社交账号', 'unlock' => ['wechat']],
            ['level' => '甜蜜恩爱', 'level_num' => 4, 'close_value' => 999, 'unlock_content' => '免费私信', 'unlock' => ['free_msg']],
//            ['level' => '真爱永恒', 'level_num' => 5, 'close_value' => 9999, 'unlock_content' => '免费通话时长', 'unlock' => ['free_call']],
        ];
    }

    /**
     * 查询功能的
     */
    static function checkFuncValue($key = '')
    {
        $setting = self::getSetting();
        $lockInfo = [];
        foreach ($setting as $item) {
            foreach ($item['unlock'] as $unlockKey) {
                if ($key == $unlockKey) return strval($item['close_value']);
            }
        }
        return '999';
    }

    /**
     * 离下个等级距离亲密值
     */
    static function getOffset($closeValue = 0)
    {
        $setting = self::getSetting();
        foreach ($setting as $k => $item) {
            if ($closeValue < $item['close_value']) {
                return [
                    'offset_value' => $item['close_value'] - $closeValue,
                    'close_value_max' => $item['close_value'],
                    'close_value_min' => $setting[$k - 1]['close_value'],
                    'level_min' => $setting[$k - 1]['level_num'],
                    'level_max' => $item['level_num'],
                    'level_min_title' => $setting[$k - 1]['level'],
                    'level_max_title' => $item['level'],
                    'unlock_func' => $setting[$k - 1]['unlock_content'],
                ];
            }
        }

        if ($closeValue >= $setting[count($setting) - 1]['close_value']) {
            return [
                'offset_value' => 0,
                'level_min' => 4,
                'level_max' => 4,
                'close_value_min' => $setting[count($setting) - 1]['close_value'],
                'close_value_max' => $setting[count($setting) - 1]['close_value'],
                'level_min_title' => $setting[count($setting) - 1]['level'],
                'level_max_title' => '',
                'unlock_func' => $setting[count($setting) - 1]['unlock_content'],
            ];
        } else {
            return [
                'offset_value' => 20,
                'level_min' => 0,
                'level_max' => 1,
                'close_value_min' => $setting[0]['close_value'],
                'close_value_max' => $setting[1]['close_value'],
                'level_min_title' => $setting[0]['level'],
                'level_max_title' => $setting[1]['level'],
                'unlock_func' => $setting[0]['unlock_content'],
            ];
        }
    }

    /**
     * 锁定功能信息
     */
    static function checkLock($closeValue = 0, $key = '')
    {
        $setting = self::getSetting();
        $lockInfo = [];
        foreach ($setting as $item) {
            foreach ($item['unlock'] as $unlockKey) {
                $lockInfo[$unlockKey] = $closeValue >= $item['close_value'] ? 0 : 1;
            }
        }
        return !$key ? $lockInfo : ($lockInfo[$key] ?? 0);
    }

    /**
     * 检测入口权限
     */
    static function checkLimit($userId, $chatUserId, $checkKey = 'video_call')
    {
        $closeValue = self::getCloseValue($userId, $chatUserId);
        return self::checkLock($closeValue, $checkKey) ? true : false;
    }

    /**
     * 是否刚达到新亲密度等级
     */
    static function checkCrossLevel($userId, $chatUserId, $addCloseValue = 0)
    {
        if ($addCloseValue == 0) return ['result' => false];
        $curCloseValue = self::getCloseValue($userId, $chatUserId);
        $closeInfo = CloseFriend::getOffset($curCloseValue);
        return [
            'result' => ($curCloseValue - $addCloseValue) < $closeInfo['close_value_min'],
            'level_title' => $closeInfo['level_min_title'],
            'level' => $closeInfo['level_min'],
            'unlock_content' => $closeInfo['unlock_func'],
            'unlock_close_value' => $closeInfo['close_value_min'],
            'cur_close_value' => $curCloseValue,
        ];
    }

    /**
     * 获取亲密度大于5的用户ID
     */
    static function getFrdListLimit($userId = 0)
    {
        $where   = ['user_id' => $userId, 'flag' => 1];
        $orWhere = ['frd_user_id' => $userId, 'flag' => 1];

        $items   = Db::table('user_close_friend')->where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->select(['user_id', 'frd_user_id', 'close_value'])->orderBy('close_value', 'desc')->get()->toArray();

        $frdIds  = [];
        foreach ($items as $item) {
            if ($item->close_value < 5) {
                continue;
            }

            $frdIds[] = $userId == $item->user_id ? $item->frd_user_id : $item->user_id;
        }

        return $frdIds;
    }
}
